package com.ruoyi.business.dto;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;

public class FileMultipartFile implements MultipartFile {
    private final File file;
    private final byte[] content;
    private final String name;
    private final String originalFilename;
    private final String contentType;

    public FileMultipartFile(File file, String contentType) throws IOException {
        this.file = file;
        try (FileInputStream fis = new FileInputStream(file);
             ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                bos.write(buffer, 0, bytesRead);
            }

            this.content = bos.toByteArray();  // ✅ Java 8兼容写法
            this.originalFilename = file.getName();
            this.name = file.getName();
            this.contentType = contentType;
        }
    }

    // 实现 MultipartFile 接口方法（同网络URL方案中的示例）
    @Override
    public String getName() {
        return name;
    }

    @Override
    public String getOriginalFilename() {
        return originalFilename;
    }

    @Override
    public String getContentType() {
        return contentType;
    }

    @Override
    public boolean isEmpty() {
        return content.length == 0;
    }

    @Override
    public long getSize() {
        return content.length;
    }

    @Override
    public byte[] getBytes() {
        return content;
    }

    @Override
    public InputStream getInputStream() {
        return new ByteArrayInputStream(content);
    }

    @Override
    public void transferTo(File dest) throws IOException {
        Files.copy(file.toPath(), dest.toPath());
    }
}
